<template>
  <div>
    <!-- 添加或修改配置参数对话`框 -->
    <el-dialog
      :model-value="open"
      :title="title"
      width="900px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="editForm"
        :model="listForms"
        :rules="rules"
        label-width="135px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input
                v-model="listForms.nickName"
                placeholder="请输入用户昵称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <el-cascader
                ref="cascaderRef"
                v-model="listForms.deptId"
                :options="deptOptions"
                :props="props1"
                clearable
                placeholder="请选择归属部门"
                :show-all-levels="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input
                v-model="listForms.phoneNumber"
                placeholder="请输入手机号"
                maxlength="11"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="listForms.email"
                placeholder="请输入邮箱"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="listForms.userId == undefined"
              label="用户账号"
              prop="userName"
            >
              <el-input
                v-model="listForms.userName"
                placeholder="请输入用户账号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="listForms.userId == undefined" label="用户密码" prop="password">
              <el-input v-model="listForms.password" placeholder="请输入用户密码" type="password"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别" prop="sex">
              <el-select
                v-model="listForms.sex"
                filterable
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="dict in dicts[DictDirection.用户性别]"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="listForms.status">
                <el-radio
                  v-for="dict in dicts[DictDirection.是否禁用字典]"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >
                  {{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职级" prop="postId">
              <el-select
                v-model="listForms.postId"
                clearable 
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in postOptions"
                  :key="item.postId"
                  :label="item.postName"
                  :value="item.postId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位" prop="roleIds">
              <el-select
                v-model="listForms.roleIds"
                filterable
                clearable
                multiple
                placeholder="请选择"
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="listForms.remark"
                type="textarea"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
            <el-divider></el-divider>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, getCurrentInstance, watch, defineExpose, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { ElTree } from 'element-plus'
import useDicts, { DictDirection } from '@/store/modules/dicts'
import { getUser, addUser, updateUser, treeselect } from '@/api/system/user'
import userStore from '@/store/modules/user'

const store = userStore()
const userInfo = computed(() => store.user)
const userInfoList = JSON.parse(JSON.stringify(userInfo.value))
const dicts = useDicts()
dicts.setDicts(DictDirection.用户性别)
defineProps<{
  open,
  title
}>()
// 部门列表
const listForms = ref({
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    password: 123456,
    phoneNumber: undefined,
    email: undefined,
    sex: undefined,   
    status: '0',
    remark: undefined,
    postId: undefined,
    roleIds: [],
  }),
  // 表单验证
  rules = {
    userName: [
      { required: true, message: '用户账号不能为空', trigger: 'blur' },
    ],
    nickName: [
      { required: true, message: '用户姓名不能为空', trigger: 'blur' },
    ],
    deptId: [{ required: true, message: '归属部门不能为空', trigger: 'blur' }],
    email: [
      { required: true, message: '邮箱地址不能为空', trigger: 'blur' },
      {
        type: 'email',
        message: '\'请输入正确的邮箱地址',
        trigger: ['blur', 'change'],
      },
    ],
    phoneNumber: [
      { required: true, message: '手机号码不能为空', trigger: 'blur' },
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur',
      },
    ],
    postId: [
      { required: true, message: '职级不能为空', trigger: 'blur' },
    ],
    status: [
      { required: true, message: '状态不能为空', trigger: 'blur' },
    ],
  }
const props1 = {
    checkStrictly: true,
    multiple: false, // 删除多选
    emitPath: false, // 只返回该节点的值
    label: 'label',
    value: 'id',
  },
  // 新增修改表单
  editForm = ref(null),
  {
    proxy,
  }:{
    proxy:any
  } = getCurrentInstance()

// 获取归属部门列表
const deptOptions = ref([])
const getdeptTreeselect = () => {
  treeselect().then((res) => {
    deptOptions.value = res.data
  })
}
getdeptTreeselect()

// 获取角色列表和岗位
const postOptions = ref([])
const roleOptions = ref([])
const deptRef = ref<InstanceType<typeof ElTree>>()
const getUserDetail = () => {
  getUser(1).then((res) => {
    const postList = JSON.parse(JSON.stringify(res.data.posts))
    const roleList = JSON.parse(JSON.stringify(res.data.roles))
    postOptions.value = postList 
    roleOptions.value = roleList
  })
}

const emit = defineEmits(['changeList', 'update:open', 'update:title'])

// 重置新增修改用户信息列表
const reset = () => {
  listForms.value = {
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    password: 123456,
    phoneNumber: undefined,
    email: undefined,
    sex: undefined,
    status: '0',
    remark: undefined,
    postId: undefined,
    roleIds: [],
  }
  proxy.$resetForm(editForm.value)
}
// 新增修改用户信息——确定
const submitForm = () => {
  proxy.$validateForm(editForm.value, () => {
    let msg = ''
    let response = null
    let userClassify = null // 用户分类
    let userType = null // 用户类型
    userClassify = '2'
    userType = '01'
    const data = {
      ...listForms.value,
      userClassify,
      userType,
    }
    if (listForms.value.userId != undefined) {
      msg = '修改成功'
      response = updateUser(data)
    } else {
      msg = '新增成功'
      response = addUser(data)
    }
    response
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success(msg)
        emit('update:open', false)
        emit('changeList')
      } else {
        ElMessage.error(res.msg)
      }
    })
    .catch((error) => {
      if (error == 'cancel') {
        ElMessage.error(error)
      }
    })
  })
}
// 修改新增用户信息——取消
const cancel = () => {
  reset()
  emit('update:open', false)
}
const form = ref(null),
  basis = ref(null)
const getList = (id) => {
  getUser(id).then((res) => {
    form.value = res.data.data
    basis.value = res.data.details ? res.data.details : {}
    listForms.value = { ...form.value }
    postOptions.value = res.data.posts   
    roleOptions.value = res.data.roles
    // listForms.value.postId = res.data.data.postId
    // listForms.value.roleIds = res.data.data.roleId
    // listForms.value.password = ''
  })
}

dicts.setDicts(DictDirection.是否禁用字典)

defineExpose({
  getList,
  listForms,
  getUserDetail,
  deptRef,
})
</script>
<style lang="less" scoped>
.information {
  line-height: 24px;
  font-size: 16px;
  color: #303133;
}
.tree_border {
  border: 0 solid #ccc;
  border-radius: 5px;
}
/deep/.el-form-item__content {
  display: inline-block;
}
</style>
